package com.foreknow.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.foreknow.entity.Fmeditem;
import com.foreknow.service.FmeditemService;
import com.foreknow.utils.Constance;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import static com.foreknow.utils.downLoadExcel.downLoadExcel;

@RestController
@RequestMapping("/fmeditem")
public class FmeditemController {
    @Autowired
    private FmeditemService fmeditemService;

    //查询所有项目信息，用于初始化列表展示
    @ApiOperation("查询所有项目信息，用于初始化列表展示")
    @RequestMapping(value = "/queryFmeditemArr",method = RequestMethod.GET)
    public String queryFmeditemArr(@RequestParam Map<String,Object> para) throws JsonProcessingException {
        HashMap<String,Object> hs =new HashMap();
        Integer pageNum =Integer.parseInt((String) para.get("pageNum"));
        Integer pageSize =Integer.parseInt((String)  para.get("pageSize"));
        //设置分页信息
        PageHelper.startPage(pageNum,pageSize);
        List list = fmeditemService.queryFmeditemArr();
        //PageInfo是PageHelper中内置的分页信息类
        PageInfo<Fmeditem> info = new PageInfo(list);
        //给map添加数据
        hs.put("total",info.getTotal());
        hs.put("pageNum",info.getPageNum());
        hs.put("list",list);
        if (list.size()>0){
            hs.put("meta",new Constance("获取项目列表成功",200));
        }else {
            hs.put("meta",new Constance("获取项目列表失败",401));
        }
        ObjectMapper objectMapper =new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }
    //查询Department所有执行科室信息，用于选择器展示
    @ApiOperation("查询Department所有执行科室信息，用于选择器展示")
    @RequestMapping(value = "/queryDeptItem",method = RequestMethod.GET)
    public String queryDeptItem(@RequestParam Map<String,Object> para) throws JsonProcessingException {
        HashMap<String,Object> hs =new HashMap();
        List list = fmeditemService.queryDeptItem();
        //给map添加数据
        hs.put("list",list);
        if (list.size()>0){
            hs.put("meta",new Constance("获取执行科室成功",200));
        }else {
            hs.put("meta",new Constance("获取执行科室失败",401));
        }
        ObjectMapper objectMapper =new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }

    //查询Expenseclass所有费用分类信息，用于选择器展示
    @ApiOperation("查询Expenseclass所有费用分类信息，用于选择器展示")
    @RequestMapping(value = "/queryExpItem",method = RequestMethod.GET)
    public String queryExpItem(@RequestParam Map<String,Object> para) throws JsonProcessingException {
        HashMap<String,Object> hs =new HashMap();
        List list = fmeditemService.queryExpItem();
        //给map添加数据
        hs.put("list",list);
        if (list.size()>0){
            hs.put("meta",new Constance("获取费用分类成功",200));
        }else {
            hs.put("meta",new Constance("获取费用分类失败",401));
        }
        ObjectMapper objectMapper =new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }

    //根据条件查询项目信息
    @ApiOperation("据条件查询项目信息")
    @RequestMapping(value = "queryFmeditem",method = RequestMethod.POST)
    @ResponseBody
    public String queryFmeditem(@RequestBody Map<String,Object> para) throws JsonProcessingException{
        HashMap<String,Object> hs=new HashMap<>();
        //获取请求参数

        Integer pageNum =Integer.parseInt((String) para.get("pageNum"));
        Integer pageSize =Integer.parseInt((String)  para.get("pageSize"));
        String itemCode = (String) para.get("itemcode");
        String itemName = (String) para.get("itemname");
        Integer expclassID=null;
        Integer deptID  =null;
        if(para.get("expclassid")!=null&&para.get("expclassid")!=""){
            expclassID  =(Integer) para.get("expclassid");
        }
        if(para.get("deptid")!=null&&para.get("deptid")!=""){
            deptID  = (Integer) para.get("deptid");
        }
        Fmeditem fmeditem=new Fmeditem();
        fmeditem.setItemcode(itemCode);
        fmeditem.setItemname(itemName);
        fmeditem.setExpclassid(expclassID);
        fmeditem.setDeptid(deptID);
        fmeditem.setFormat("");
        fmeditem.setPrice(0);
        fmeditem.setRecordtype(1);
        fmeditem.setCreationdate(null);
        fmeditem.setLastupdatedate(null);
        fmeditem.setMnemoniccode(null);
        fmeditem.setDelmark(1);

        PageHelper.startPage(pageNum,pageSize);

        List list = fmeditemService.selectFmed(fmeditem);

        PageInfo<Fmeditem> info = new PageInfo(list);
        hs.put("list",list);
        hs.put("total",info.getTotal());
        hs.put("pageNum",info.getPageNum());
        //添加meta
        if (list.size()>=0){
            hs.put("meta",new Constance("根据条件获取项目信息成功",200));
        }else {
            hs.put("meta",new Constance("根据条件获取项目信息失败",401));
        }
        ObjectMapper objectMapper =new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }

    //添加项目信息
    @ApiOperation("添加项目信息")
    @RequestMapping(value = "insertFmeditem",method = RequestMethod.POST)
    @ResponseBody
    public String insertFmeditem(@RequestBody Map<String,Object> para) throws JsonProcessingException {
        //获取表单信息
        HashMap<String,Object> hs = new HashMap<>();
        String itemCode = (String) para.get("itemcode");
        String itemName = (String) para.get("itemname");
        String format = (String) para.get("format");
        String mnemoniccode = (String) para.get("mnemoniccode");
        Double price = Double.parseDouble((String) para.get("price"));
        Integer expclassID  = (Integer) para.get("expclassid");
        Integer deptID  = (Integer) para.get("deptid");
        Integer recordType  = (Integer) para.get("recordtype");
        Date creationdate = new Date();
        Date lastupdatedate = null;

        Fmeditem fmeditem=new Fmeditem();
        fmeditem.setItemcode(itemCode);
        fmeditem.setItemname(itemName);
        fmeditem.setExpclassid(expclassID);
        fmeditem.setFormat(format);
        fmeditem.setPrice(price);
        fmeditem.setDeptid(deptID);
        fmeditem.setRecordtype(recordType);
        fmeditem.setCreationdate(creationdate);
        fmeditem.setLastupdatedate(lastupdatedate);
        fmeditem.setMnemoniccode(mnemoniccode);
        fmeditem.setDelmark(1);

        int isRight = fmeditemService.insert(fmeditem);
        if(isRight==1){
            hs.put("meta",new Constance("添加项目成功",200));
        }else {
            hs.put("meta",new Constance("添加项目失败",401));
        }
        ObjectMapper objectMapper =new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }

    //通过id查询项目信息，用于更新前数据回显
    @ApiOperation("通过id查询项目信息，用于更新前数据回显")
    @RequestMapping(value = "selectFmeditemById",method = RequestMethod.GET)
    public String selectFmeditemById(@RequestParam Map<String,Object>para) throws JsonProcessingException {
        //获取表单信息
        HashMap<String,Object> hs = new HashMap<>();
        Integer id =Integer.parseInt((String) para.get("id"));
        Fmeditem fmeditem=fmeditemService.selectByPrimaryKey(id);
        hs.put("item",fmeditem);
        if (fmeditem!=null){
            hs.put("meta",new Constance("根据id获取项目信息成功",200));
        }else {
            hs.put("meta",new Constance("根据id获取项目信息失败",401));
        }
        ObjectMapper objectMapper = new ObjectMapper();
        return  objectMapper.writeValueAsString(hs);
    }


    //根据id修改项目信息
    @ApiOperation("根据id修改项目信息")
    @RequestMapping(value = "updateFmed" ,method = RequestMethod.POST)
    public String updateFmedById(@RequestBody Map<String,Object> para) throws JsonProcessingException {
        //获取表单信息
        HashMap<String,Object> hs = new HashMap<>();
        Integer ID  = Integer.parseInt((String) para.get("id"));
        String itemCode = (String) para.get("itemcode");
        String itemName = (String) para.get("itemname");
        String format = (String) para.get("format");
        String mnemoniccode = (String) para.get("mnemoniccode");
        Double price = Double.parseDouble((String) para.get("price"));
        Integer expclassID  = (Integer) para.get("expclassid");
        Integer deptID  = (Integer) para.get("deptid");
        Integer recordType  = (Integer) para.get("recordtype");
        Date creationdate = null;
        Date lastupdatedate = new Date();

        Fmeditem fmeditem=new Fmeditem();
        fmeditem.setId(ID);
        fmeditem.setItemcode(itemCode);
        fmeditem.setItemname(itemName);
        fmeditem.setExpclassid(expclassID);
        fmeditem.setFormat(format);
        fmeditem.setPrice(price);
        fmeditem.setDeptid(deptID);
        fmeditem.setRecordtype(recordType);
        fmeditem.setCreationdate(creationdate);
        fmeditem.setLastupdatedate(lastupdatedate);
        fmeditem.setMnemoniccode(mnemoniccode);
        fmeditem.setDelmark(1);

        //调用service修改方法
        int isRight = fmeditemService.updateByPrimaryKey(fmeditem);
        if (isRight==1){
            hs.put("meta",new Constance("修改项目成功",200));
        }else {
            hs.put("meta",new Constance("修改项目失败",401));
        }
        ObjectMapper objectMapper = new ObjectMapper();
        return  objectMapper.writeValueAsString(hs);
    }

    //根据id删除项目信息
    @ApiOperation("根据id删除项目信息")
    @RequestMapping(value = "deleteFmedById" ,method = RequestMethod.GET)
    public String deleteFmedById(@RequestParam Map<String,Object>para) throws JsonProcessingException {
        HashMap<String,Object> hs=new HashMap<>();
        Integer id = Integer.parseInt((String)para.get("id"));
        int isRight = fmeditemService.deleteFmedById(id);
        if (isRight==1){
            hs.put("meta",new Constance("删除项目成功",200));
        }else {
            hs.put("meta",new Constance("删除项目失败",401));
        }
        ObjectMapper objectMapper =new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }

    //批量删除项目信息
    @ApiOperation("批量删除项目信息")
    @RequestMapping(value = "deleteByChoose",method = RequestMethod.POST)
    public String deleteByChoose(@RequestBody Map<String ,Object> para) throws JsonProcessingException {
        HashMap<String,Object> hs=new HashMap<>();
        List<Integer> arr = new ArrayList<Integer>();;
        arr= (List<Integer>) para.get("info");

        int sum =0;
        int isRight =0;
        for(Integer ss:arr
        ) {
            isRight = fmeditemService.deleteFmedById(ss);
            sum = sum + isRight;
        }
        if (sum==arr.size()){
            hs.put("meta",new Constance("批量删除项目成功",200));
        }else {
            hs.put("meta",new Constance("批量删除项目失败",401));
        }
        ObjectMapper objectMapper =new ObjectMapper();
        return objectMapper.writeValueAsString(hs);

    }

    //从文件批量上传项目信息
    @ApiOperation("从文件批量上传项目信息")
    @RequestMapping(value = "/ExcelInsertFmed", method = RequestMethod.POST)
    @ResponseBody
    public String ExcelInsertFmed(@RequestParam("excelFile") MultipartFile excelFile) throws JsonProcessingException {
        String name = excelFile.getOriginalFilename();
        ObjectMapper objectMapper =new ObjectMapper();
        HashMap<String,Object> hs=new HashMap<>();
        try {
            if(fmeditemService.excelToList(excelFile.getInputStream())>0) {
                hs.put("meta",new Constance("批量添加成功",200));
                return objectMapper.writeValueAsString(hs);
            }else {
                hs.put("meta",new Constance("批量添加失败",401));
                return objectMapper.writeValueAsString(hs);
            }
        } catch (Exception e) {
            e.printStackTrace();
            hs.put("meta",new Constance("批量添加失败",401));
            return objectMapper.writeValueAsString(hs);
        }
    }

    @ApiOperation("从前端下载数据模版")
    @RequestMapping(value="/downloadExcel", method = RequestMethod.POST)
    public ResponseEntity<Resource> excel2007Export(HttpServletResponse response, HttpServletRequest request) {
        try {
            ClassPathResource cpr = new ClassPathResource("/templates/" + "Fmeditem.xlsx");
            InputStream is = cpr.getInputStream();
            Workbook workbook = new XSSFWorkbook(is);
            String fileName = "Fmeditem.xlsx";
            downLoadExcel(fileName, response, workbook);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return new ResponseEntity<Resource>(HttpStatus.OK);
    }

}
